package com.im.strive.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.im.strive.R;
import com.im.strive.model.beans.OpenResource;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadFileListener;


/**
 * Created by jiangwei on 16/4/26.
 */
public class ShareActivity extends AppCompatActivity implements View.OnClickListener{

    private static final int REQUEST_CODE = 8090;
    private TextView mTvUpLoadSpeed , mTvUpLoadFileLength ,  mTvUpLoadPercentage;
    private ProgressBar mPb;
    private ImageView mIvResult;
    private String uploadFilePath;
    private LinearLayout mLnStatus;
    private Button mBtnSelect , mBtnUpLoad;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_share);
        initView();
        listener();
    }




    private void initView() {
        mPb = (ProgressBar) findViewById(R.id.pb_share_image_upload_progressbar);
        mPb.setMax(100);

        mTvUpLoadFileLength = (TextView) findViewById(R.id.tv_share_upload_file_length);
        mTvUpLoadPercentage = (TextView) findViewById(R.id.tv_share_image_upload_percentage);
        mTvUpLoadSpeed = (TextView) findViewById(R.id.tv_share_upload_speed);

        mIvResult = (ImageView) findViewById(R.id.iv_share_quick_start);

        mLnStatus = (LinearLayout) findViewById(R.id.ln_share_upload_status_layout);

        mBtnSelect = (Button) findViewById(R.id.btn_share_select);
        mBtnUpLoad = (Button) findViewById(R.id.btn_share_upload);
    }


    private void listener() {
        mBtnSelect.setOnClickListener(this);
        mBtnUpLoad.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_share_select:
                Intent target = com.im.strive.utils.FileUtils.createGetContentIntent();
                Intent intent = Intent.createChooser(target ,this.getString(R.string.choose_file));

                this.startActivityForResult(intent , REQUEST_CODE);
                Log.i("uploadFilePath" , uploadFilePath + ",result");
                break;
            case R.id.btn_share_upload:
                upLoadFile();
                break;

        }
    }

    private void upLoadFile() {

        final BmobFile file = new BmobFile(new File(uploadFilePath));
        file.uploadblock(ShareActivity.this, new UploadFileListener() {
            @Override
            public void onSuccess() {

               String a = file.getFileUrl(ShareActivity.this);
                String filename = file.getFilename();
                Toast.makeText(ShareActivity.this , "上传成功!"  ,Toast.LENGTH_LONG).show();
                saveFileURL(a , filename);
            }

            @Override
            public void onProgress(Integer value) {
                super.onProgress(value);
                mPb.setProgress(value);
            }

            @Override
            public void onFailure(int i, String s) {
                Toast.makeText(ShareActivity.this ,  s + "" ,Toast.LENGTH_LONG).show();
            }
        });


//        if (this.uploadFilePath == null){
//            return;
//
//        }
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                final OkHttpClient httpClient = new OkHttpClient();
//                Request req = new Request.Builder().url(QiniuLabConfig.makeUrl(
//                        QiniuConfig.REMOTE_SERVICE_SERVER,
//                        QiniuConfig.QUICK_START_IMAGE_DEMO_PATH)).method("GET", null).build();
//                Response resp = null;
//                try {
//                    resp=httpClient.newCall(req).execute();
//                    JSONObject jsonObject = new JSONObject(resp.body().string());
//                    String uploadToken = jsonObject.getString("uptoken");
//                    String domain = jsonObject.getString("domain");
//
//                    upload(uploadToken, domain);
//                } catch (Exception e) {
//                    AsyncRun.run(new Runnable() {
//                        @Override
//                        public void run() {
//                            Toast.makeText(
//                                    context,
//                                    context.getString(R.string.qiniu_get_upload_token_failed),
//                                    Toast.LENGTH_LONG).show();
//                        }
//                    });
//                    Log.e(QiniuLabConfig.LOG_TAG,e.getMessage());
//                }finally {
//                    if(resp!=null){
//                        try {
//                            resp.body().close();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
//            }
//        }).start();
    }

    private void saveFileURL(String path , String filename) {

        OpenResource source = new OpenResource();
        source.setFileurl(path);
        source.setFilename(filename);
        source.save(ShareActivity.this, new SaveListener() {
            @Override
            public void onSuccess() {
                Log.i("sourceok" , "ok");
            }



            @Override
            public void onFailure(int i, String s) {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case REQUEST_CODE:
                if (resultCode == RESULT_OK){
                    if (data != null) {
                        // Get the URI of the selected file
                        final Uri uri = data.getData();
                        try {
                            // Get the file path from the URI
                            final String path = com.im.strive.utils.FileUtils.getPath(this ,uri);
                            this.uploadFilePath = path;
                            Log.i("uploadFilePath" , uploadFilePath + "");
                        } catch (Exception e) {
                            Toast.makeText(
                                    ShareActivity.this,
                                  "选择上传文件失败!",
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                }


        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
